package io;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;

/**
 * @author Mr.Sun
 * @date 2022年08月31日 22:24
 *
 *  文件读写的实用工具
 */
public class TextFile extends ArrayList<String> {

    /**
     * 读取单个文件
     *
     * @param filename 文件名称
     * @return 文件内容
     */
    public static String read(String filename) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader in = new BufferedReader(new FileReader(
                    new File(filename).getAbsoluteFile()));
            try {
                String s;
                while ((s = in.readLine()) != null) {
                    sb.append(s);
                    sb.append("\n");
                }
            } finally {
                in.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sb.toString();
    }

    /**
     * 向文件中写内容
     *
     * @param filename 文件名称
     * @param text 内容
     */
    public static void write(String filename, String text) {
        try {
            PrintWriter out = new PrintWriter(new File(filename).getAbsoluteFile());
            try {
                out.print(text);
            } finally {
                out.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 读取文件，由任何正则表达式拆分
     *
     * @param filename 文件名称
     * @param splitter 分隔符
     */
    public TextFile(String filename, String splitter) {
        super(Arrays.asList(read(filename).split(splitter)));
        // 正则表达式split() 通常在第一个位置留下一个空字符串
        if (get(0).equals("")) {
            remove(0);
        }
    }

    public TextFile(String filename) {
        this(filename, "\n");
    }

    public void write(String filename) {
        try {
            PrintWriter out = new PrintWriter(new File(filename).getAbsoluteFile());
            try {
                for (String item : this) {
                    out.println(item);
                }
            } finally {
                out.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String filename = "src/io/TextFile.java";
        String file = read(filename);
        write("test.txt", file);
        TextFile text = new TextFile("test.txt");
        text.write("test2.txt");
        // 拆分为单词的唯一排序列表
        TreeSet<String> words = new TreeSet<>(
                new TextFile(filename, "\\W+"));

        // 显示大写的单词
        System.out.println(words.headSet("a"));
    }
}
